package com.ys.controller.api.account;

import com.ys.config.MenuId;
import com.ys.entity.account.TbAdvanceType;
import com.ys.entity.account.TcwAdvanceAccountDetail;
import com.ys.entity.sys.YsCol;
import com.ys.service.account.TcwAdvanceAccountDetailService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 预支台账明细
 */
@Controller
@RequestMapping("/api/inter/tcwAdvanceAccountDetail")
public class ApiInterTcwAdvanceAccountDetailController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwAdvanceAccountDetailController.class);

    @Autowired
    private CommonApiService<TcwAdvanceAccountDetail> commonApiService;

    @Autowired
    private TcwAdvanceAccountDetailService tcwAdvanceAccountDetailService;

    @Autowired
    private CheckUtil checkUtil;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwAdvanceAccountDetail setSeachSql(TcwAdvanceAccountDetail cond){

        cond.addLeftJoin("TCW_AdvanceAccount P ON P.Id = A.Pid")//预支账户管理
                .addField("P.Code AS pCode")//预支账户编码
                .addField("P.Name AS pName")//预支账户名称

                .addLeftJoin("TB_AdvanceType T ON T.Code = A.AdvanceTypeCode")//预支类型
                .addField("T.Name AS advanceTypeName")//预支类型名称

                .addLeftJoin("TB_CompanyInfo C ON C.Vid = A.CompanyInfoVid")//公司信息表
                .addField("C.Vname AS companyName")//公司名称

                .addLeftJoin("THR_OperateCompanyApply OC ON OC.Vgsbm = A.Vgsbm")//运营公司表
                .addField("OC.Vgsjc AS vgsjc");//公司简称

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS userName")//新增人员
                .addField("U.DeptName AS deptName");//新增部门

        //排序
        cond.setOrderby("A.Pid ASC");

        cond = commonApiService.dataAuth(MenuId.TCW_AdvanceAccountDetail, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwAdvanceAccountDetail:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwAdvanceAccountDetail cond
    ){
        try {
            cond = setSeachSql(cond);

            return commonApiService.searchLay(cond);
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwAdvanceAccountDetail cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_AdvanceAccountDetail)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TbAdvanceType> util = new ExportExcelUtils<>(new TbAdvanceType());
            String toFilePath = util.exportExcel(listData, listField, "预支账户管理明细");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwAdvanceAccountDetailService.add(params,MenuId.TCW_AdvanceAccountDetail);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwAdvanceAccountDetailService.update(params,MenuId.TCW_AdvanceAccountDetail);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 划拨，生成流水
     */
    @RequiresPermissions("tcwAdvanceAccountDetail:doTransferFlow")
    @RequestMapping("/doTransferFlow")
    @ResponseBody
    public R doTransferFlow(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            String resMsg = "";
            int count = 0;
            for (int i=0;i<idList.size();i++){
                R res = tcwAdvanceAccountDetailService.doTransferFlow(Long.parseLong(idList.get(i)));
                if(res.getCode().equals( R.Code.FAILED.value)){
                    resMsg += "划拨的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
                }else {
                    count++;
                }

            }
            return R.ok("成功操作"+count+"条数据</br>"+resMsg);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 复制
     */
    @RequiresPermissions("tcwAdvanceAccountDetail:copy")
    @RequestMapping("/doCopy")
    @ResponseBody
    public R doCopy(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            for (int i=0;i<idList.size();i++){
                tcwAdvanceAccountDetailService.doCopy(Long.parseLong(idList.get(i)));

            }
            return R.ok();
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }




    /**
     * 删除
     */
    @RequiresPermissions("tcwAdvanceAccountDetail:del")
    @RequestMapping("/doDelByList")
    @ResponseBody
    public R doDelByList(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            String resMsg = "";
            int count = 0;
            for (int i=0;i<idList.size();i++){
                R res = tcwAdvanceAccountDetailService.doDel(Long.parseLong(idList.get(i)));
                if(res.getCode().equals( R.Code.FAILED.value)){
                    resMsg += "删除的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
                }else {
                    count++;
                }

            }
            return R.ok("成功操作"+count+"条数据</br>"+resMsg);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 批量设置成本价
     */
    @RequiresPermissions("tcwAdvanceAccountDetail:setUnitPrice")
    @RequestMapping("/setUnitPrice")
    @ResponseBody
    public R setUnitPrice(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {

            if(checkUtil.isNullByObject(params.get("unitPrice"))){
                return R.error("请输入成本价");
            }
            if(!checkUtil.checkNumber( params.get("unitPrice").toString())){
                return R.error("成本价应为数字");
            }
            BigDecimal unitPrice = new BigDecimal(params.get("unitPrice").toString());
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            String resMsg = "";
            int count = 0;
            for (int i=0;i<idList.size();i++){
                R res = tcwAdvanceAccountDetailService.setUnitPrice(Long.parseLong(idList.get(i)),unitPrice);
                if(res.getCode().equals( R.Code.FAILED.value)){
                    resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
                }else {
                    count++;
                }

            }
            return R.ok("成功操作"+count+"条数据</br>"+resMsg);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 批量设置代理价
     */
    @RequiresPermissions("tcwAdvanceAccountDetail:setProxyPrice")
    @RequestMapping("/setProxyPrice")
    @ResponseBody
    public R setProxyPrice(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {

            if(checkUtil.isNullByObject(params.get("proxyPrice"))){
                return R.error("请输入代理价");
            }
            if(!checkUtil.checkNumber( params.get("proxyPrice").toString())){
                return R.error("代理价应为数字");
            }
            BigDecimal proxyPrice = new BigDecimal(params.get("proxyPrice").toString());
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            String resMsg = "";
            int count = 0;
            for (int i=0;i<idList.size();i++){
                R res = tcwAdvanceAccountDetailService.setProxyPrice(Long.parseLong(idList.get(i)),proxyPrice);
                if(res.getCode().equals( R.Code.FAILED.value)){
                    resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
                }else {
                    count++;
                }

            }
            return R.ok("成功操作"+count+"条数据</br>"+resMsg);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



    /**
     * 批量修改预支类型
     */
    @RequiresPermissions("tcwAdvanceAccountDetail:setAdvanceType")
    @RequestMapping("/setAdvanceType")
    @ResponseBody
    public R setAdvanceType(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {

            if(checkUtil.isNullByObject(params.get("advanceTypeCode"))){
                return R.error("请选择预支类型");
            }

            String advanceTypeCode = params.get("advanceTypeCode").toString();
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            String resMsg = "";
            int count = 0;
            for (int i=0;i<idList.size();i++){
                R res = tcwAdvanceAccountDetailService.setAdvanceType(Long.parseLong(idList.get(i)),advanceTypeCode);
                if(res.getCode().equals( R.Code.FAILED.value)){
                    resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
                }else {
                    count++;
                }

            }
            return R.ok("成功操作"+count+"条数据</br>"+resMsg);
        } catch (IllegalArgumentException e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


    /**
     * 弹出框
     */
    @RequestMapping("/searchForModal")
    @ResponseBody
    public LayuiTableVoJA searchForModal(@ModelAttribute TcwAdvanceAccountDetail cond,String conditions){

        cond = setSeachSql(cond);
        //cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId")//人员变动信息
                //.addField("U.UserName AS userName")//新增人员
                //.addField("U.DeptName AS deptName");//新增部门
        cond.setStatus(1);
        cond.setDetailType(0);//未报销的
        cond.setTransferStatus(1);//已划拨的
        /*
        String pid = ConditionUtil.getConditionValue(conditions, "pid");//pid

        if(pid!=null && !"".equals(pid)){
            cond.where("A.Pid = "+ Long.parseLong(pid));
        }
        System.out.println("pid::"+pid);
         */

        return commonApiService.searchLay(cond);
    }



    /**
     * 删除
     */
    @RequestMapping("/toDel")
    @ResponseBody
    public R toDel(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwAdvanceAccountDetailService.delTrue(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }


}